package org.bluedash.tryssl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;

public class SSLServer extends Thread {
	private Socket socket;

	public SSLServer(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		try {
			//从socket中取得输入流,并用Reader读取流内容,以获得Reader对象
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			//从socket中取得输出流,并用其建立Writer对象
			PrintWriter writer = new PrintWriter(socket.getOutputStream());
			//读取内容
			String data = reader.readLine();
			
			System.out.println("---------------" + data);
			//使用PrintWriter打印出内容
			writer.println(data);
			writer.close();
			socket.close();
		} catch (IOException e) {
		}
	}

	public static void main(String[] args) throws Exception {
		System.setProperty("javax.net.ssl.trustStore", Constant.SERVER_KEY_STORE);
		SSLContext context = SSLContext.getInstance("TLS");

		KeyStore ks = KeyStore.getInstance("jks");
		ks.load(new FileInputStream(Constant.SERVER_KEY_STORE), null);
		KeyManagerFactory kf = KeyManagerFactory.getInstance("SunX509");
		kf.init(ks, Constant.SERVER_KEY_STORE_PASSWORD.toCharArray());

		//加载key管理器到SSLContext中,
		context.init(kf.getKeyManagers(), null, null);
		//从context中获取ServerSocketFactory对象
		ServerSocketFactory factory = context.getServerSocketFactory();
		//这步是建立socket连接的最关键:从工厂中取得一个指定端口的Socket对象,建立对应的连接
		SSLServerSocket _socket = (SSLServerSocket)factory.createServerSocket(Constant.PORT);
		//不需要客户端授权
		_socket.setNeedClientAuth(false);
		//启动线程
		while (true) {
			new SSLServer(_socket.accept()).start();
		}
	}
}